using System;
using System.Linq;
using System.Text.RegularExpressions;
using BuildBox.Core.Server.Adapters;

namespace BuildBox.Core.Server.Requests
{
    public static class RequestHandlersExtensions
    {
        public static bool CanHandle(this Request target, IHttpListenerRequestAdapter request)
        {
            string localPath = request.Url.LocalPath;
            if (localPath.StartsWith(request.Configuration.VirtualDirectory))
            {
                localPath = localPath.Substring(request.Configuration.VirtualDirectory.Length);
                if (localPath.Length == 0)
                {
                    localPath = "/";
                }
            }

            Regex regex = new Regex(target.UrlPattern);
            var match = regex.Match(localPath);
            return match.Success && target.Verbs.Any(v => v.Equals(request.HttpMethod, StringComparison.InvariantCultureIgnoreCase));
        }
    }
}